package com.ziqikeji.socket.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * 服务器端从客户端接收数据的线程类
 * @author bcs
 */
public class GetInputStream extends Thread {
    private Socket r;
    public GetInputStream(Socket r) {
        this.r = r;
    }
    @Override
    public void run() {
        try {
            //获取输入流
            InputStreamReader is = new InputStreamReader(r.getInputStream());
            BufferedReader br = new BufferedReader(is);
            while (true) {
                //读取客户端发送过来的消息
                String msg = br.readLine();
                System.out.println(msg);
                //读取客户端发送过来的消息后转发给所有在线的客户端
                for (Socket socket : MyServer.sockets) {
                    OutputStreamWriter osw = new OutputStreamWriter(
                            socket.getOutputStream());
                    BufferedWriter bw = new BufferedWriter(osw);
                    bw.write(msg + "\n");
                    //刷新流
                    bw.flush();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
